package com.zzedu.framework.config;

import com.zzedu.system.service.ISysUserOnlineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

public class KeyExpirationListener extends KeyExpirationEventMessageListener {
    Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysUserOnlineService userOnlineService;

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public KeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        log.info("会话【" + key + "】已过期");
        // 处理会话超时的逻辑
        clearSession(key);
    }


    /**
     * 清理回话
     *
     * @param key
     */
    private void clearSession(String key) {
        String fixKey = ":token:sessions:";
        if (key.contains(fixKey)) {
            String sid = key.substring(key.indexOf(fixKey) + fixKey.length(), key.length());
            userOnlineService.deleteOnlineById(sid);
        }
    }
}
